package com.greate.mqtt.springbootmqttdemo.config;


import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

/**
 * mqtt发布端（没有订阅topic）
 * @author v_zhangshun01
 */
@RestController
@RequestMapping("/mqtt")
@Component
public class PlatformMqtt implements MqttCallback {

	private final static Logger log = LoggerFactory.getLogger(PlatformMqtt.class);

	@Value("${mqtt.server}")
	private String host;

	@Value("${mqtt.username}")
	private String name;

	@Value("${mqtt.password}")
	private String passWord;

	private MqttClient client;


	String clientId = String.valueOf(System.currentTimeMillis());

	@PostConstruct
	public void send() {
		try {
			client = new MqttClient(host, clientId, new MemoryPersistence());

		} catch (MqttException e) {
			e.printStackTrace();
		}

		MqttConnectOptions options = new MqttConnectOptions();

		options.setCleanSession(false);

		options.setUserName(name);

		options.setPassword(passWord.toCharArray());

		// 设置超时时间
		options.setConnectionTimeout(10);

		// 设置会话心跳时间
		options.setKeepAliveInterval(3600);

		try {
			client.setCallback(this);

			client.connect(options);
		} catch (Exception e) {
			log.info("platform-Mqtt客户端连接异常，异常信息：" + e);
		}

	}

	@PostMapping("/request")
	@ResponseBody
	public void publish(@RequestBody MqttDTO mqttDTO) throws MqttException {
		String body = mqttDTO.getMessage();
		String topic = mqttDTO.getTopic();
		log.info("请求主题为：" + topic + ",消息为：" + body);
		MqttMessage message = new MqttMessage();
		message.setQos(0);
		message.setRetained(false);
		message.setPayload(body.getBytes());
		client.publish(topic, message);
	}

	@Override
	public void connectionLost(Throwable throwable) {
		log.info("程序出现异常，正在重新连接...:");
		try {
			client.close();
			send();
		} catch (MqttException e) {
			log.info(e.getMessage());
		}
		log.info("platform-Mqtt重新连接成功");
	}

	@Override
	public void messageArrived(String s, MqttMessage mqttMessage) {
		System.out.println("客户端接收到数据：" + s);

		System.out.println(mqttMessage);
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
		log.info("消息发送成功");
	}
}
